import Vue from 'vue'; // 导入vue
import Preview from './index.vue'; // 导入组件

// 将组件作为参数，使用vue提供的全局方法，创建一个构造函数
let PreviewConstructor = Vue.extend(Preview);

const preview = function ({ url = undefined, on = {}, config = {}, ...args }) {
	let instance = null;
	let availWidth = window.innerWidth;
	let availHeight = window.innerHeight;
	let ratio = window.screen.width / (1920 * getRatio());
	let defaultConfig = {
		config: {
			active: true,
			w: 600,
			minw: 160,
			minh: 90,
			deviation: 50, // 安全距离
			ratio: 16 / 10,
			index: 0,
			availWidth,
			availHeight,
			z: 2147483,
		},
	};

	defaultConfig.config.w = defaultConfig.config.w * ratio;
	defaultConfig.config.h ??= defaultConfig.config.w / defaultConfig.config.ratio;
	defaultConfig.config.x ??= availWidth - defaultConfig.config.w - defaultConfig.config.deviation;
	defaultConfig.config.y ??= availHeight - defaultConfig.config.h - defaultConfig.config.deviation;
	// 初始化实例，此时instance是一个组件实例，但未初始化未完成
	instance = new PreviewConstructor({
		name: 'previewDialog',
		data: {
			url,
			on,
			config: Object.assign(defaultConfig.config, config),
			...args,
		},
		methods: {
			unmount() {
				unmount();
			},
		},
	});
	const unmount = () => {
		if (instance !== null) {
			instance.show = false;
			// document.body.removeChild(instance.$el);
		}
	};
	// 卸载组件

	// 完成初始化
	instance.$mount();

	// 将组件添加到根节点body
	// document.body.appendChild(instance.$el);
	document.body.insertBefore(instance.$el, document.body.firstChild);
	// instance.show = true;
	return unmount;
};

//获取屏幕缩放比例
function getRatio() {
	var ratio = 0;
	var screen = window.screen;
	var ua = navigator.userAgent.toLowerCase();

	if (window.devicePixelRatio !== undefined) {
		ratio = window.devicePixelRatio;
	} else if (~ua.indexOf('msie')) {
		if (screen.deviceXDPI && screen.logicalXDPI) {
			ratio = screen.deviceXDPI / screen.logicalXDPI;
		}
	} else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
		ratio = window.outerWidth / window.innerWidth;
	}

	return ratio;
}
function getFileType(fileName) {
	const fileNameSplit = fileName.split('.');
	const fileExt = fileNameSplit[fileNameSplit.length - 1].toLowerCase();
	let type = 'other';
	if (this.imgTypesList.includes(fileExt)) {
		type = 'img';
	}
	if (this.docxTypesList.includes(fileExt)) {
		type = 'docx';
	}
	if (this.pdfTypesList.includes(fileExt)) {
		type = 'pdf';
	}
	if (this.xlsxTypesList.includes(fileExt)) {
		type = 'xlsx';
	}
	if (this.txtTypesList.includes(fileExt)) {
		type = 'txt';
	}
	return type;
}
export default preview;
